package com.automannn.atm_back.modules.codeGenerator.core.service;


import com.automannn.atm_back.modules.codeGenerator.core.pojo.Callback;
import com.automannn.atm_back.modules.codeGenerator.core.pojo.GlobalConfig;
import com.automannn.atm_back.modules.codeGenerator.core.pojo.TableInfo;
import com.automannn.atm_back.modules.codeGenerator.core.pojo.Template;
import com.automannn.atm_back.modules.codeGenerator.core.util.*;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenkh
 * @time 2020/7/6 13:58
 */
@Component("velocityCodeService")
public class VelocityCodeService implements CodeService {

    @Override
    public String generate(Template template, TableInfo tableInfo, Collection<GlobalConfig> globalConfigs) {
        //1.获取默认参数(包括java工具方法)
        Map<String, Object> param = getJavaParam();
        param.put("tableInfo", tableInfo);
        Callback callback = new Callback();
        // 设置回调对象
        param.put("callback", callback);
        //2.设置模型路径和导包列表
        setModulePathAndImportList(param, tableInfo);
        //3.处理模板,注入全局变量
        TemplateUtils.addGlobalConfig(template, globalConfigs);
        //4.调用工具进行生成
        String result = VelocityUtils.generate(template.getCode(), param).trim();

        // 清除前面空格
        result = result.trim();
        // 设置一个默认保存路径与默认文件名
        if (StringUtils.isEmpty(callback.getFileName())) {
            callback.setFileName(tableInfo.getName() + "Default.java");
        }
        if (StringUtils.isEmpty(callback.getSavePath())) {
            callback.setSavePath(tableInfo.getSavePath());
        }
        String path = callback.getSavePath();
        path = path.replace("\\", "/");

        String fileName = callback.getFileName();
        //写入文件
        FileUtils.getInstance().write(result,path,fileName);
        //5.处理回调
        return result;
    }

    private void setModulePathAndImportList(Map<String, Object> param, TableInfo tableInfo) {
        param.put("modulePath", "com.automannn.codeTest");
        param.put("importList", "com.automannn.test.*");
    }

    //todo：将这个方法抽象成接口
    private Map<String, Object> getJavaParam() {
        Map<String, Object> param = new HashMap<>(20);
        // 作者
        param.put("author", "automannn");
        //工具类
        param.put("tool", GlobalTool.getInstance());
        param.put("time", TimeUtils.getInstance());
        return param;
    }
}
